package com.donghua.controller;

import com.donghua.entity.*;
import com.donghua.service.CommentService;
import com.donghua.service.DiscussPostService;
import com.donghua.service.LikeService;
import com.donghua.service.UserService;
import com.donghua.util.*;
import com.donghua.vo.PostDetailVO;
import com.donghua.vo.PostVO;
import com.donghua.vo.UserDetailInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import static com.donghua.enums.StatusCodeEnum.*;

@Controller
@RequestMapping("/post")
public class DiscussPostController implements CommunityConstant {

    @Autowired
    private DiscussPostService discussPostService;

    @Autowired
    private UserService userService;

    @Autowired
    private CommentService commentService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LikeService likeService;

    @Autowired
    private HostHolder hostHolder;


    @RequestMapping(path = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Result<?> addDiscussPost(PostVO postVO) {
        System.out.println("adfasdf");
        //插入帖子
        User user = hostHolder.getUser();
        DiscussPost post = new DiscussPost();
        post.setUserId(user.getId());
        post.setTitle(postVO.getTitle());
        post.setContent(postVO.getContent());
        post.setCreateTime(new Date());
        int postId = discussPostService.addDiscussPost(post);

        //插入标签和帖子标签对应表
        for(int i = 0; i < postVO.getTags().size(); i++) {
            int tagCount = discussPostService.findTagCountByTagName(postVO.getTags().get(i));
            int tagId;
            if(tagCount == 0) {
                Tag tag = new Tag();
                tag.setTagName(postVO.getTags().get(i));
                tag.setCreateTime(new Date());
                tag.setTagCount(1);
                tagId = discussPostService.addTag(tag);
            } else {
                Tag tag = discussPostService.findTagByTagName(postVO.getTags().get(i));
                //tagCount++
                discussPostService.updateTagCountByTagName(tag.getTagName());
                tagId = tag.getId();
            }
            DiscussPostTag discussPostTag = new DiscussPostTag();
            discussPostTag.setPostId(postId);
            discussPostTag.setTagId(tagId);
            discussPostService.addDiscussPostTag(discussPostTag);
        }
        //插入图片
        for(int i = 0; i < postVO.getMfs().length; i++) {
            Picture picture = new Picture();
            picture.setPostId(postId);
            discussPostService.uploadPicture(postVO.getMfs()[i], picture);
        }

        return Result.ok(SUCCESS.getCode(), SUCCESS.getMsg());
    }

    @RequestMapping(path = "/detail/{discussPostId}", method = RequestMethod.GET)
    @ResponseBody
    public Result<?> getDiscussPost(@PathVariable("discussPostId") int discussPostId, int offset, int limit, HttpServletRequest request) {
        // 帖子
        PostDetailVO postDetailVO = new PostDetailVO();
        DiscussPost post = discussPostService.findDiscussPostById(discussPostId);
        Map<String, Object> data = new HashMap<>();
        postDetailVO.setId(post.getId());
        postDetailVO.setTitle(post.getTitle());
        postDetailVO.setContent(post.getContent());
        postDetailVO.setCreateTime(post.getCreateTime());
        postDetailVO.setScore(post.getScore());
        postDetailVO.setType(post.getType());
        postDetailVO.setStatus(post.getStatus());
        postDetailVO.setUserId(post.getUserId());
        post.setUserId(post.getId());
        //帖子对应的标签
        //插入tag对应的id
        List<Integer> tagIds = new ArrayList<>();
        List<String> tagNames = discussPostService.getDiscussPostTags(post.getId());
        for(String tagName : tagNames) {
            tagIds.add(discussPostService.findTagIdByTagName(tagName));
        }
        List<Map<String, Object>> tags = new ArrayList<>();
        for(int i = 0; i < tagNames.size(); i++) {
            Map<String, Object> tag = new HashMap<>();
            tag.put("tagId", tagIds.get(i));
            tag.put("tagName", tagNames.get(i));
            tags.add(tag);
        }
        postDetailVO.setTags(tags);
        // 作者
        User user = userService.findUserById(postDetailVO.getUserId());
        UserDetailInfo userDetailInfo = new UserDetailInfo();
        userDetailInfo.setId(user.getId());
        userDetailInfo.setNickName(user.getNickName());
        userDetailInfo.setDescription(user.getDescription());
        userDetailInfo.setUsername(user.getUsername());
        userDetailInfo.setType(user.getType());
        userDetailInfo.setStatus(user.getStatus());
        userDetailInfo.setCreateTime(user.getCreateTime());
        userDetailInfo.setHeaderUrl(user.getHeaderUrl());
        userDetailInfo.setBackgroundUrl(user.getBackgroundUrl());
        data.put("user", userDetailInfo);
        // 点赞数量
        long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_POST, discussPostId);
        postDetailVO.setLikeCount(likeCount);
        // 回帖数量
        int commentCount = commentService.findCommentCount(ENTITY_TYPE_POST, discussPostId);
        postDetailVO.setCommentCount(commentCount);
        // 从cookie中获取凭证
        String ticket = CookieUtil.getValue(request, "ticket");
        boolean flag = false;
        if (ticket != null) {
            // 查询凭证
            String redisKey = RedisKeyUtil.getTicketKey(ticket);
            LoginTicket loginTicket = (LoginTicket) redisTemplate.opsForValue().get(redisKey);
            // 检查凭证是否有效
            if (loginTicket != null && loginTicket.getStatus() == 0 && loginTicket.getExpired().after(new Date())) {
                // 根据凭证查询用户
                User userNew = userService.findUserById(loginTicket.getUserId());
                hostHolder.setUser(userNew);
                flag = true;
            }
        }
        // 点赞状态
        int likeStatus = !flag ? 0 :
                likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_POST, post.getId());
        postDetailVO.setLikeStatus(likeStatus);
        // 帖子对应的图片
        List<Picture> pics = discussPostService.findPicturesByPostId(post.getId());
        List<String> picUrls = new ArrayList<>();
        for(int i = 0; i < pics.size(); i++) {
            picUrls.add(pics.get(i).getPictureUrl());
        }
        postDetailVO.setPictureUrls(picUrls);
        data.put("post", postDetailVO);
        // 评论: 给帖子的评论
        // 回复: 给评论的评论
        // 评论列表
        List<Comment> commentList = commentService.findCommentsByEntity(
                ENTITY_TYPE_POST, post.getId(), offset, limit);
        // 评论VO列表
        List<Map<String, Object>> commentVoList = new ArrayList<>();
        if (commentList != null) {
            for (Comment comment : commentList) {
                // 评论VO
                Map<String, Object> commentVo = new HashMap<>();
                // 评论
                commentVo.put("comment", comment);
                // 作者
                User user2 = userService.findUserById(comment.getUserId());
                UserDetailInfo userDetailInfo2 = new UserDetailInfo();
                userDetailInfo2.setId(user2.getId());
                userDetailInfo2.setNickName(user2.getNickName());
                userDetailInfo2.setDescription(user2.getDescription());
                userDetailInfo2.setUsername(user2.getUsername());
                userDetailInfo2.setType(user2.getType());
                userDetailInfo2.setStatus(user2.getStatus());
                userDetailInfo2.setCreateTime(user2.getCreateTime());
                userDetailInfo2.setHeaderUrl(user2.getHeaderUrl());
                userDetailInfo2.setBackgroundUrl(user2.getBackgroundUrl());
                commentVo.put("user", userDetailInfo2);
                // 点赞数量
                likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeCount", likeCount);
                // 点赞状态
                likeStatus = !flag ? 0 :
                        likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("likeStatus", likeStatus);

                // 回复列表
                List<Comment> replyList = commentService.findCommentsByEntity(
                        ENTITY_TYPE_COMMENT, comment.getId(), 0, 3);
                // 回复VO列表
                List<Map<String, Object>> replyVoList = new ArrayList<>();
                if (replyList != null) {
                    for (Comment reply : replyList) {
                        Map<String, Object> replyVo = new HashMap<>();
                        // 回复
                        replyVo.put("reply", reply);
                        // 作者
                        User user3 = userService.findUserById(reply.getUserId());
                        UserDetailInfo userDetailInfo3 = new UserDetailInfo();
                        userDetailInfo3.setId(user3.getId());
                        userDetailInfo3.setNickName(user3.getNickName());
                        userDetailInfo3.setDescription(user3.getDescription());
                        userDetailInfo3.setUsername(user3.getUsername());
                        userDetailInfo3.setType(user3.getType());
                        userDetailInfo3.setStatus(user3.getStatus());
                        userDetailInfo3.setCreateTime(user3.getCreateTime());
                        userDetailInfo3.setHeaderUrl(user3.getHeaderUrl());
                        userDetailInfo3.setBackgroundUrl(user3.getBackgroundUrl());
                        replyVo.put("user", userDetailInfo3);
                        // 回复目标
                        User target = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                        replyVo.put("target", target);
                        // 点赞数量
                        likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeCount", likeCount);
                        // 点赞状态
                        likeStatus = !flag ? 0 :
                                likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, reply.getId());
                        replyVo.put("likeStatus", likeStatus);
                        replyVoList.add(replyVo);
                    }
                }
                commentVo.put("replys", replyVoList);

                // 回复数量
                int replyCount = commentService.findCommentCount(ENTITY_TYPE_COMMENT, comment.getId());
                commentVo.put("replyCount", replyCount);
                commentVoList.add(commentVo);
            }
        }
        data.put("comments", commentVoList);
        return Result.ok(SUCCESS.getCode(), SUCCESS.getMsg(), data);
    }

    @RequestMapping(path = "/replyDetail")
    @ResponseBody
    public Result<?> getReplyDetail(int entityId) {
        // 回复列表
        List<Comment> replyList = commentService.findCommentsByEntity(
                ENTITY_TYPE_COMMENT, entityId, 0, Integer.MAX_VALUE);
        // 回复VO列表
        List<Map<String, Object>> data = new ArrayList<>();
        if (replyList != null) {
            for (Comment reply : replyList) {
                Map<String, Object> replyVo = new HashMap<>();
                // 回复
                replyVo.put("reply", reply);
                // 作者
                User user3 = userService.findUserById(reply.getUserId());
                UserDetailInfo userDetailInfo3 = new UserDetailInfo();
                userDetailInfo3.setId(user3.getId());
                userDetailInfo3.setNickName(user3.getNickName());
                userDetailInfo3.setDescription(user3.getDescription());
                userDetailInfo3.setUsername(user3.getUsername());
                userDetailInfo3.setType(user3.getType());
                userDetailInfo3.setStatus(user3.getStatus());
                userDetailInfo3.setCreateTime(user3.getCreateTime());
                userDetailInfo3.setHeaderUrl(user3.getHeaderUrl());
                userDetailInfo3.setBackgroundUrl(user3.getBackgroundUrl());
                replyVo.put("user", userDetailInfo3);
                // 回复目标
                User target = reply.getTargetId() == 0 ? null : userService.findUserById(reply.getTargetId());
                replyVo.put("target", target);
                // 点赞数量
                long likeCount = likeService.findEntityLikeCount(ENTITY_TYPE_COMMENT, reply.getId());
                replyVo.put("likeCount", likeCount);
                // 点赞状态
                int likeStatus = hostHolder.getUser() == null ? 0 :
                        likeService.findEntityLikeStatus(hostHolder.getUser().getId(), ENTITY_TYPE_COMMENT, reply.getId());
                replyVo.put("likeStatus", likeStatus);
                data.add(replyVo);
            }
        }
        return Result.ok(SUCCESS.getCode(), SUCCESS.getMsg(), data);
    }
}
